//
//  MainViewController.swift
//  Practice
//
//  Created by miaozhihui on 2016/11/24.
//  Copyright © 2016年 DeKuTree. All rights reserved.
//

import UIKit
import SVProgressHUD

class MainViewController: UITabBarController {

    /// 定时器
    fileprivate var timer:Timer?
    
    // MARK: - 视图生命周期函数
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        
        setupComposedButton()
        
        setupTimer()
        
        setupNewFeatureViews()
        
        delegate = self
        
        // 注册 需要登录 通知
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserNeedLoginNotification), object: nil)
    }

    deinit {
        // 释放定时器
        timer?.invalidate()
        
        // 注销通知
        NotificationCenter.default.removeObserver(self)
    }
    
    /*
     portrait: 竖屏，肖像
     landscape: 横屏，风景画
     */
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .portrait
    }
    
    // MARK: - 监听方法
    /// 点击撰写按钮
    @objc fileprivate func clickComposedButton() {
        
        // FIXME: 判断是否登录
        
        // 实例化视图
        let v = ComposeTypeView.composeTypeView()
        
        // 显示视图
        v.show {[weak v] (clsName) in
            print(clsName ?? "")
            
            guard let clsName = clsName,
                let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? UIViewController.Type
                else {
                    v?.removeFromSuperview()
                    return
                }
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            self.present(nav, animated: true, completion: {
                v?.removeFromSuperview()
            })
        }
    }
    
    /// 用户登录处理
    @objc private func userLogin(n:Notification) {
        print("用户登录通知\(n)")
        
        var deadLine:DispatchTime = .now()
        
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.black)
            SVProgressHUD.showInfo(withStatus: "登录超时，请重新登录!")
            deadLine = .now()+2
        }
        DispatchQueue.main.asyncAfter(deadline: deadLine) {
            SVProgressHUD.setDefaultMaskType(.clear)
            let nav = UINavigationController(rootViewController: OAuthViewController())
            
            self.present(nav, animated: true, completion: nil)
        }
    }
    
    fileprivate lazy var composedButton:UIButton = UIButton(
        imageName: "tabbar_compose_icon_add",
        backImageName: "tabbar_compose_button")
}

// MARK: - 新特性视图处理
extension MainViewController {
    
    /// 设置新特性视图
    fileprivate func setupNewFeatureViews() {
        if !NetworkTools.sharedTools.userLogon {
            return
        }
        let v = isNewVersion ? NewFeatureView.newFeatureView() : WelcomeView.welcomeView()
        view.addSubview(v)
    }
    
    private var isNewVersion: Bool {
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print(currentVersion)
        let path: String = ("version" as NSString).xs_appendDocumentDir()
        let sandboxVersion = (try? String(contentsOfFile: path)) ?? ""
        print(sandboxVersion)
        print(path)
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        return currentVersion != sandboxVersion
    }
}

// MARK: - tabbar控制器代理方法
extension MainViewController: UITabBarControllerDelegate {
    
    /// 将要选中控制器
    ///
    /// - Parameters:
    ///   - tabBarController: tabBarController
    ///   - viewController: 目标控制器
    /// - Returns: 是否切换到目标控制器
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要切换到\(viewController)")
        // 获取将要选中控制器索引
        let index = (childViewControllers as NSArray).index(of: viewController)
        // 如果当前选中索引是首页，并且将要选中索引是当前索引，重复点击首页按钮
        if selectedIndex == 0 && index == selectedIndex {

            let nav = childViewControllers[0] as! CustomNavigationController
            
            let vc = nav.childViewControllers[0] as! HomeController
            
            //vc.tableView?.setContentOffset(CGPoint(x: 0, y: -64), animated: false)
            // 需要注意：如果使用动画，可能会造成页面显示不正常(不能滚动到顶部)
            vc.tableView?.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
            // 使用动画的话，需要延迟执行下边代码
            DispatchQueue.main.asyncAfter(deadline: .now()+0.25, execute: {
               vc.loadData()
            })
            
            // 清除 tabbarItem 的 badgeNumber 和 app 的 iconBadgeNumber
            vc.tabBarItem.badgeValue = nil
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        return !viewController.isMember(of: UIViewController.self)
    }
}

// MARK: - 定时器相关方法
extension MainViewController {
    
    /// 实例化定时器
    fileprivate func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
    }
    
    /// 定时器触发方法
    @objc private func updateTimer() {
        // 如果没有登录，不需要请求接口
        if !NetworkTools.sharedTools.userLogon {
            return
        }
        
        NetworkTools.sharedTools.unreadMessage { (count) in
            self.tabBar.items?[0].badgeValue = count > 0 ? "\(count)" : nil
            UIApplication.shared.applicationIconBadgeNumber = count
        }
    }
}

// MARK: - 设置界面
extension MainViewController {
    
    /// 设置所有子控制器
    fileprivate func setupChildControllers() {
        
        // 获取沙盒 json 路径
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("main.json")
        
        // 加载 data
        var data = NSData(contentsOfFile: jsonPath)
        
        // 判断 data 是否有内容
        if data == nil {
            let path = Bundle.main.path(forResource: "main", ofType: "json")
            data = NSData(contentsOfFile: path!)
        }
        
        // 反序列化转化为数组
        guard let array = try? JSONSerialization.jsonObject(with: data as! Data, options: []) as? [[String:Any]] else {
            return
        }
        
        // 遍历数组，循环创建控制器数组
        var arrayM = [UIViewController]()
        for dict in array! {
            arrayM.append(controller(dict: dict))
        }
        viewControllers = arrayM
    }
    
    /// 使用字典创建一个子控制器
    ///
    /// - Parameter dict: 信息字典
    /// - Returns: 子控制器
    private func controller(dict:[String:Any]) -> UIViewController {
        
        guard let clsName = dict["clsName"] as? String,let title = dict["title"] as? String,let imageName = dict["imageName"] as? String,let cls = NSClassFromString(Bundle.main.nameSpace+"."+clsName) as? BaseController.Type,let visitorDict = dict["visitorInfo"] as? [String:String]  else {
            return UIViewController()
        }
        
        let vc = cls.init()
        
        vc.title = title
        
        // 设置控制器的访客信息字典
        vc.visitorInfo = visitorDict

        // 测试从网络获取图标
//        if let imageData = NSData(contentsOf: URL(string: imageName)!) {
//            vc.tabBarItem.image = UIImage(data: imageData as Data)
//        }
        
        vc.tabBarItem.image = UIImage(named: "tabbar_"+imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_"+imageName+"_selected")?.withRenderingMode(.alwaysOriginal)
        // 设置标题样式
        vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 10)], for: .normal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orange], for: .highlighted)
        
        let nav = CustomNavigationController(rootViewController: vc)
        
        return nav
    }
    
    /// 设置撰写按钮
    fileprivate func setupComposedButton() {
        // 添加按钮
        tabBar.addSubview(composedButton)
        // 调整按钮
        let count = childViewControllers.count
        let w = tabBar.bounds.width / CGFloat(count)
        composedButton.frame = tabBar.bounds.insetBy(dx: 2*w, dy: 0)
        // 添加监听方法
        composedButton.addTarget(self, action: #selector(clickComposedButton), for: .touchUpInside)
    }
    
}
